<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form class="-mb-15px" :model="queryParams" ref="queryFormRef" :inline="true">
      <el-form-item :label="t('interview.fields.batchId')" prop="batchId">
        <el-select
          v-model="queryParams.batchId"
          :placeholder="t('common.selectTextPlaceholder') + t('interview.fields.batchId')"
          clearable
          class="!w-160px"
          :disabled="advancedSearching"
          @change="handleQuery"
        >
          <el-option
            v-for="(item, index) in batchOptions"
            :key="index"
            :label="item.batchName"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery" :disabled="advancedSearching">
          <Icon icon="ep:search" class="mr-5px" />
          {{ t('common.search') }}
        </el-button>
        <el-button @click="resetQuery" :disabled="advancedSearching">
          <Icon icon="ep:refresh" class="mr-5px" />
          {{ t('common.reset') }}
        </el-button>
        <el-button
          type="primary"
          plain
          @click="openForm('create')"
          v-hasPermi="['recruit:interview:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" />
          {{ t('action.add') }}
        </el-button>
        <!--        <el-button-->
        <!--          type="warning"-->
        <!--          plain-->
        <!--          @click="handleImport"-->
        <!--          v-hasPermi="['recruit:interview:export']"-->
        <!--        >-->
        <!--          <Icon icon="ep:upload" class="mr-5px" />-->
        <!--          {{ t('action.import') }}-->
        <!--        </el-button>-->
        <!--        <el-button-->
        <!--          type="success"-->
        <!--          plain-->
        <!--          @click="handleExport"-->
        <!--          :loading="exportLoading"-->
        <!--          v-hasPermi="['recruit:interview:export']"-->
        <!--        >-->
        <!--          <Icon icon="ep:download" class="mr-5px" />-->
        <!--          {{ t('action.export') }}-->
        <!--        </el-button>-->
        <!--        <ConditionTree-->
        <!--          id="interview-condition-tree"-->
        <!--          :schemata="interviewSchema"-->
        <!--          @search="handleAdvanceSearch"-->
        <!--        />-->
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <vxe-toolbar ref="toolbarRef" custom />
    <vxe-table
      id="iInterview-table"
      ref="tableRef"
      v-loading="loading"
      :data="list"
      stripe
      :custom-config="vxeTableConfig"
      :column-config="{ resizable: true }"
      :size="vxeTableSize"
    >
      <vxe-column :title="t('common.index')" type="seq" field="seq" width="60" align="center" />
      <vxe-column
        :title="t('interview.fields.batchId')"
        field="batchId"
        align="center"
        show-header-overflow
        show-overflow
        min-width="100"
      >
        <template #default="scope">
          {{ batchOptions.find((item) => item.id === scope.row.batchId)?.batchName }}
        </template>
      </vxe-column>
      <vxe-column
        :title="t('interview.fields.status')"
        field="status"
        align="center"
        show-header-overflow
        show-overflow
        min-width="100"
      >
        <template #default="scope">
          {{ calculateStatus(scope.row) }}
        </template>
      </vxe-column>
      <vxe-column
        :title="t('interview.fields.interviewDate')"
        field="interviewDate"
        align="center"
        show-header-overflow
        show-overflow
        min-width="100"
        :formatter="vxeDateFormatter2"
      />
      <vxe-column
        :title="t('interview.fields.groups')"
        field="groups"
        align="center"
        show-header-overflow
        show-overflow
        min-width="100"
      />
      <vxe-column
        :title="t('interview.fields.interviewTimes')"
        field="interviewTimes"
        align="center"
        show-header-overflow
        show-overflow
        min-width="100"
      />
      <vxe-column
        :title="t('interview.fields.studentLimit')"
        field="studentLimit"
        align="center"
        show-header-overflow
        show-overflow
        min-width="100"
      />
      <vxe-column
        :title="t('interview.fields.studentLimitAm')"
        field="studentLimitAm"
        align="center"
        show-header-overflow
        show-overflow
        min-width="100"
        :visible="false"
      />
      <vxe-column
        :title="t('interview.fields.studentLimitPm')"
        field="studentLimitPm"
        align="center"
        show-header-overflow
        show-overflow
        min-width="100"
        :visible="false"
      />
      <vxe-column
        :title="t('interview.fields.interviewDuration')"
        field="interviewDuration"
        align="center"
        show-header-overflow
        show-overflow
        min-width="100"
        :visible="false"
      >
        <template #default="scope">
          {{ scope.row.interviewDuration }} {{ t('interview.form.min') }}
        </template>
      </vxe-column>
      <vxe-column
        :title="t('interview.fields.interviewGap')"
        field="interviewGap"
        align="center"
        show-header-overflow
        show-overflow
        min-width="100"
        :visible="false"
      >
        <template #default="scope">
          {{ scope.row.interviewGap }} {{ t('interview.form.min') }}
        </template>
      </vxe-column>
      <vxe-column
        :title="t('interview.fields.interviewStartTime')"
        field="interviewStartTime"
        align="center"
        show-header-overflow
        show-overflow
        min-width="100"
        :visible="false"
      />
      <vxe-column
        :title="t('interview.fields.interviewEndTime')"
        field="interviewEndTime"
        align="center"
        show-header-overflow
        show-overflow
        min-width="100"
        :visible="false"
      />
      <vxe-column
        :title="t('interview.fields.launchStartTime')"
        field="launchStartTime"
        align="center"
        show-header-overflow
        show-overflow
        min-width="100"
        :visible="false"
      />
      <vxe-column
        :title="t('interview.fields.launchEndTime')"
        field="launchEndTime"
        align="center"
        show-header-overflow
        show-overflow
        min-width="100"
        :visible="false"
      />
      <vxe-column
        :title="t('interview.fields.unassignedCount')"
        field="unassignedCount"
        align="center"
        show-header-overflow
        show-overflow
        min-width="100"
      />
      <vxe-column
        :title="t('interview.fields.studentCount')"
        field="studentCount"
        align="center"
        show-header-overflow
        show-overflow
        min-width="100"
      />
      <vxe-column
        :title="t('interview.fields.createTime')"
        field="createTime"
        align="center"
        show-header-overflow
        show-overflow
        min-width="100"
        :formatter="vxeDateFormatter"
        :visible="false"
      />
      <vxe-column
        :title="t('common.operate')"
        field="operator"
        align="center"
        fixed="right"
        width="200"
      >
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="openForm('update', scope.row.id)"
            v-hasPermi="['recruit:interview:update']"
          >
            {{ t('action.edit') }}
          </el-button>
          <el-button
            link
            type="primary"
            @click="handleSetGroup(scope.row.id)"
            v-hasPermi="['recruit:interview:update']"
          >
            {{ t('interview.index.setGroup') }}
          </el-button>
          <el-button
            link
            type="primary"
            @click="handleStudentList(scope.row)"
            v-hasPermi="['recruit:interview:update']"
          >
            {{ t('interview.index.studentList') }}
          </el-button>
          <el-button
            link
            type="primary"
            @click="handleExportStudentList(scope.row)"
            v-hasPermi="['recruit:interview:update']"
            :disabled="scope.row.studentCount === 0"
          >
            {{ t('interview.index.exportStudentList') }}
          </el-button>
          <!--<el-button-->
          <!--  link-->
          <!--  type="danger"-->
          <!--  @click="handleDelete(scope.row.id)"-->
          <!--  v-hasPermi="['recruit:interview:delete']"-->
          <!-- >-->
          <!--  {{ t('action.delete') }}-->
          <!--</el-button>-->
        </template>
      </vxe-column>
    </vxe-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <InterviewForm ref="formRef" @success="getList" />
  <ExcelImportForm
    ref="importFormRef"
    object-name="面试"
    upload-url="/recruit/interview/import"
    template-url="/recruit/interview/get-import-template"
    @success="getList"
  />

  <InterviewGroupList ref="interviewGroupRef" />

  <RecruitStudentListInInterview ref="studentListRef" />
</template>

<script setup lang="ts">
import { formatDate, vxeDateFormatter, vxeDateFormatter2 } from '@/utils/formatTime'
import download from '@/utils/download'
import { InterviewApi, InterviewVO } from '@/api/recruit/interview'
import InterviewForm from './InterviewForm.vue'
import ExcelImportForm from '@/components/ExcelImportForm/index.vue'
import type { VxeTableInstance, VxeTablePropTypes, VxeToolbarInstance } from 'vxe-table'
import { interviewSchema } from '@/views/recruit/interview/schema'
import { useAppStore } from '@/store/modules/app'
import { BatchApi, BatchVO } from '@/api/recruit/batch'
import InterviewGroupList from '@/views/recruit/interviewgroup/components/InterviewGroupList.vue'
import RecruitStudentListInInterview from '@/views/recruit/recruitstudent/components/RecruitStudentListInInterview.vue'
import { StudentApi } from '@/api/recruit/recruitstudent'

/** 面试 列表 */
defineOptions({ name: 'Interview' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const toolbarRef = ref<VxeToolbarInstance>()
const tableRef = ref<VxeTableInstance>()
const interviewGroupRef = ref<InstanceType<typeof InterviewGroupList>>()

const loading = ref(true) // 列表的加载中
const list = ref<InterviewVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const advancedSearching = ref(false) // 高级搜索
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  advanced: undefined,
  batchId: undefined,
  interviewDate: [],
  studentLimit: undefined,
  studentLimitAm: undefined,
  studentLimitPm: undefined,
  interviewDuration: undefined,
  interviewGap: undefined,
  interviewStartTime: [],
  interviewEndTime: [],
  launchStartTime: [],
  launchEndTime: [],
  status: undefined,
  interviewTimes: undefined,
  groups: undefined,
  remark: undefined,
  createTime: []
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

const vxeTableConfig: VxeTablePropTypes.CustomConfig = {
  storage: true,
  mode: 'drawer',
  checkMethod({ column }) {
    return !['seq', 'operator'].includes(column.field)
  }
}

const appStore = useAppStore()
const vxeTableSize = computed(() => appStore.getCurrentSizeVxe)

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await InterviewApi.getInterviewPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  advancedSearching.value = false
  ;(queryParams as any).advanced = undefined
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref<InstanceType<typeof InterviewForm>>()
const openForm = (type: string, id?: string) => {
  formRef.value?.open(type, id)
}

/** 导入 */
const importFormRef = ref<InstanceType<typeof ExcelImportForm>>()
const handleImport = () => {
  importFormRef.value?.open()
}

/** 删除按钮操作 */
const handleDelete = async (id: string) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await InterviewApi.deleteInterview(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await InterviewApi.exportInterview(queryParams)
    download.excel(data, '面试.xlsx')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

const handleAdvanceSearch = (base64Advanced?: string) => {
  ;(queryParams as any).advanced = base64Advanced
  advancedSearching.value = !!base64Advanced
  handleQuery()
}

const batchOptions = ref<BatchVO[]>([])
const getBatchSelectOptions = async () => {
  batchOptions.value = await BatchApi.getSelectList()
}

// 根据时间判断状态，未到面试日期则是未开始，面试前一天状态是即将开始，面试当天并起始时间未结束则是进行中，已过面试日期则是已结束
const calculateStatus = (row: InterviewVO) => {
  const now = new Date()
  const interviewDate = new Date(row.interviewDate)

  // 获取面试当天的开始和结束时间
  const startDateTime = new Date(interviewDate)
  const endDateTime = new Date(interviewDate)

  const [startHour, startMinute, startSecond] = row.interviewStartTime.split(':').map(Number)
  const [endHour, endMinute, endSecond] = row.interviewEndTime.split(':').map(Number)

  startDateTime.setHours(startHour, startMinute, startSecond, 0)
  endDateTime.setHours(endHour, endMinute, endSecond, 0)

  if (now < startDateTime) {
    return t('interview.status.notStarted')
  } else if (now >= startDateTime && now < endDateTime) {
    return t('interview.status.ongoing')
  } else if (now >= endDateTime) {
    return t('interview.status.ended')
  } else {
    // 面试前一天
    const oneDayBefore = new Date(interviewDate)
    oneDayBefore.setDate(interviewDate.getDate() - 1)

    if (now >= oneDayBefore && now < startDateTime) {
      return t('interview.status.comingSoon')
    }
  }
}

/**
 * 设置分组弹窗
 *
 * @param id 面试ID
 */
const handleSetGroup = (id: string) => {
  interviewGroupRef.value?.show(id)
}

const studentListRef = ref<InstanceType<typeof RecruitStudentListInInterview>>()
const handleStudentList = (id: InterviewVO) => {
  studentListRef.value?.open(id)
}

const handleExportStudentList = async (row: InterviewVO) => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
  } catch {
    return
  }
  try {
    const data = await StudentApi.exportStudentGroupingList({
      batchId: row.batchId,
      interviewId: row.id
    })
    const batchName = batchOptions.value.find((item) => item.id === row.batchId)?.batchName
    const date = row.interviewDate ? formatDate(row.interviewDate, 'YYYY-MM-DD') : ''
    download.excel(data, `${batchName}${date}学生名单.xlsx`)
  } catch {
    message.error(t('common.exportFailed'))
  }
}

/** 初始化 **/
onMounted(async () => {
  await getBatchSelectOptions()
  // 然后查询最新计划的数据
  queryParams.batchId = batchOptions.value[0]?.id ?? undefined
  getList()

  const table = tableRef.value
  const toolbar = toolbarRef.value
  if (table && toolbar) {
    table.connect(toolbar)
  }
})
</script>

<style lang="scss" scoped>
:deep(.vxe-cell .el-button + .el-button) {
  margin-left: 0;
}

:deep(.el-form--inline .el-form-item) {
  margin-right: 15px !important;
}
</style>
